﻿<?php
/**
  * wechat php test
  */
//define your token
//定义TOKEN密钥
define("TOKEN", "weixin");
//实例化微信对象
$wechatObj = new wechatCallbackapiTest();
//验证成功后，注释掉valid方法
if($_GET["echostr"]){
    $wechatObj->valid();
}else{
    //开启自动回复功能
    $wechatObj->responseMsg();
}
//定义类文件
class wechatCallbackapiTest
{
	//实现valid验证方法：实现对接微信公众平台
	public function valid()
    {
    	//接收随机字符串
        $echoStr = $_GET["echostr"];
        //valid signature , option
        //进行用户数字签名验证
        if($this->checkSignature()){
        	//如果成功,则返回接收到的随机字符串
            header('content-type:text');
            ob_clean();
            echo $echoStr;
        	//退出
        	exit;
        }
    }
    //定义自动回复功能
    public function responseMsg()
    {
		//get post data, May be due to the different environments
		//接收用户发送过来的XML数据
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
      	//extract post data
		if (!empty($postStr)){
                
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                //接收用户发送的关键字
                $keyword = trim($postObj->Content);
                //接收用户发送类型
                $msgType=$postObj->MsgType;
                $Event = $postObj->Event;
                $time = time();
                //文本发送模板
                $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";
                //图片发送模板
                $newsTpl="<xml>
                          <ToUserName><![CDATA[%s]]></ToUserName>
                          <FromUserName><![CDATA[%s]]></FromUserName>
                          <CreateTime>%s</CreateTime>
                          <MsgType><![CDATA[%s]]></MsgType>
                          <ArticleCount>%s</ArticleCount>
                          %s
                          </xml>";
                //音乐发送模板
                $musicTpl="<xml>
                           <ToUserName><![CDATA[%s]]></ToUserName>
                           <FromUserName><![CDATA[%s]]></FromUserName>
                           <CreateTime>%s</CreateTime>
                           <MsgType><![CDATA[%s]]></MsgType>
                           <Music>
                           <Title><![CDATA[%s]]></Title>
                           <Description><![CDATA[%s]]></Description>
                           <MusicUrl><![CDATA[%s]]></MusicUrl>
                           <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
                           </Music>
                           </xml>";
                //上报地理位置模板
                $locationTpl="<xml>
                              <ToUserName><![CDATA[%s]]></ToUserName>
                              <FromUserName><![CDATA[%s]]></FromUserName>
                              <CreateTime>%s</CreateTime>
                              <MsgType><![CDATA[%s]]></MsgType>
                              <Event><![CDATA[%s]]></Event>
                              <Latitude>%s</Latitude>
                              <Longitude>%s</Longitude>
                              <Precision>%s</Precision>
                              </xml>";
                if($Event=='subscribe'){
                    $msgType = "news";
                    //设置返回图文数量
                    $count=5;
                    //设置要回复的图文数据
                    $str="<Articles>";
                    for($i=1;$i<=5;$i++){
                        $str.="<item>
                               <Title><![CDATA[我的最爱{$i}]]></Title>
                               <Description><![CDATA[开心幸福时刻]]></Description>
                               <PicUrl><![CDATA[http://sgm4231.duapp.com/images/{$i}.jpg]]></PicUrl>
                               <Url><![CDATA[http://shop96810618.m.jxsg.com/]]></Url>
                               </item>";
                    }
                    $str.="</Articles>";
                    //格式化字符串
                    $resultStr = sprintf($newsTpl, $fromUsername, $toUsername, $time, $msgType, $count,$str);
                    echo $resultStr;
                }
				if($keyword=='幸福一家')
                {
                    $msgType = "news";
                    //设置返回图文数量
                    $count=5;
                    //设置要回复的图文数据
                    $str="<Articles>";
                    for($i=1;$i<=5;$i++){
                        $str.="<item>
                               <Title><![CDATA[我的最爱{$i}]]></Title>
                               <Description><![CDATA[开心幸福时刻]]></Description>
                               <PicUrl><![CDATA[http://sgm4231.duapp.com/images/{$i}.jpg]]></PicUrl>
                               <Url><![CDATA[http://shop96810618.m.jxsg.com/]]></Url>
                               </item>";
                    }
                    $str.="</Articles>";
                    //格式化字符串
                    $resultStr = sprintf($newsTpl, $fromUsername, $toUsername, $time, $msgType, $count,$str);
                    echo $resultStr;
                    exit;
                } elseif ($keyword=="音乐")
                {
                    $msgType="music";
                    $title='爱你一万年';
                    $desc='爱你一万年，此情永流传...';
                    $url="http://sgm4231.duapp.com/music.mp3";
                    $hqurl="http://sgm4231.duapp.com/music.mp3";
                    $resultStr=sprintf($musicTpl, $fromUsername, $toUsername, $time, $msgType, $title, $desc, $url, $hqurl);
                    echo $resultStr;
                    exit;
                }else {
                    //回复类型
                	$msgType="text";
                	//定义URL
                    $url= "http://www.tuling123.com/openapi/api?key=c16a153cabad461fb1ca928b7cc059a3&info={$keyword}";
                    $ch = curl_init();
                    $timeout = 5;
                    curl_setopt ($ch, CURLOPT_URL, $url);
                    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
                    $file_contents = curl_exec($ch);
                    curl_close($ch);
                    $json = json_decode($file_contents);
                    //定义回复内容
                    $contentStr=$json->text;
                    $resultStr=sprintf($textTpl,$fromUsername, $toUsername, $time, $msgType,$contentStr);
                    echo $resultStr;
                }
        }else {
        	echo "";
        	exit;
        }
    }

	private function checkSignature()
	{
		//接收微信加密签名
        $signature = $_GET["signature"];
        //接收时间戳
        $timestamp = $_GET["timestamp"];
        //接收随机数
        $nonce = $_GET["nonce"];

		$token = TOKEN;
		//把相关参数组装成数组
		$tmpArr = array($token, $timestamp, $nonce);
		//通过字典法进行排序
		sort($tmpArr);
		//把排序后的数组转化为字符串
		$tmpStr = implode( $tmpArr );
		//通过哈希算法对字符串加密
		$tmpStr = sha1( $tmpStr );
		//与加密签名进行对比
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}

